// pages/FilmListPage/FilmListPage.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    filmList: [] as any[],
    type: '',
    title: '',
    keyword: '', // 搜索关键词
    start: 0,
    count: 20,
    hasMore: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    const { type, title, keyword } = options;
    this.setData({
      type: type || '',
      title: title || '电影列表',
      keyword: keyword || ''
    });
    
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: title || '电影列表'
    });
    
    this.loadFilmList();
  },

  // 加载电影列表
  loadFilmList() {
    const { type, start, count, keyword } = this.data;
    
    wx.showLoading({
      title: '加载中...'
    });

    // 根据不同类型使用不同的API
    let url = '';
    let requestData: any = {
      start,
      count,
      for_mobile: 1,
      ck: "sew4"
    };

    if (type === 'search') {
      // 搜索使用搜索API
      url = 'https://m.douban.com/rexxar/api/v2/search/movie';
      requestData.q = keyword;
    } else if (type === 'movie_suggestion') {
      // 猜你喜欢使用特殊的API
      url = 'https://m.douban.com/rexxar/api/v2/movie/suggestion';
      requestData.new_struct = 1;
      requestData.with_review = 1;
    } else {
      // 其他榜单使用通用API
      url = `https://m.douban.com/rexxar/api/v2/subject_collection/${type}/items`;
    }

    wx.request({
      url,
      method: "GET",
      data: requestData,
      success: (result: any) => {
        wx.hideLoading();
        // 调试用：查看API返回的数据结构
        // console.log("搜索返回数据：", result);
        // console.log("搜索类型：", type);
        
        // 根据不同API获取数据
        let newList = [];
        if (type === 'search') {
          // 搜索API返回的数据在 target 字段中
          const searchItems = result.data?.items || [];
          newList = searchItems.map((item: any) => item.target);
          // console.log("搜索结果列表：", newList);
        } else if (type === 'movie_suggestion') {
          newList = result.data?.items || [];
        } else {
          newList = result.data?.subject_collection_items || [];
        }
        
        // 统一数据格式，确保有 cover_url 字段
        const formattedList = newList.map((item: any) => ({
          ...item,
          cover_url: item.cover_url || item.cover?.url || item.cover?.large || item.cover?.normal || item.pic?.normal || ''
        }));
        
        this.setData({
          filmList: [...this.data.filmList, ...formattedList],
          start: this.data.start + count,
          hasMore: newList.length >= count
        });
      },
      fail: (error) => {
        wx.hideLoading();
        console.log("加载失败：", error);
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
      }
    });
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore) {
      this.loadFilmList();
    }
  }
})

